package com.tiantian.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tiantian.bean.PageBean;
import com.tiantian.dao.BackstageRoleRepository;
import com.tiantian.dao.BackstageUserRepository;
import com.tiantian.dao.BackstageUserRoleRepository;
import com.tiantian.datajpa.service.impl.GenericServiceImpl;
import com.tiantian.domain.BackstageRole;
import com.tiantian.domain.BackstageUser;
import com.tiantian.domain.BackstageUserRole;
import com.tiantian.ret.Result;
import com.tiantian.service.BackstageUserService;
import com.tiantian.service.vo.UserVo;
import com.tiantian.util.CommonConstant.QueryType;
import com.tiantian.util.ConditionResult;

/**
 * 后台管理用户
 * 
 * @author xiaoqiang
 * 
 */
@Service
@Transactional
public class BackstageUserServiceImpl extends GenericServiceImpl<BackstageUser, String> implements BackstageUserService {
	private BackstageUserRepository repository;
	@Autowired
	private BackstageUserRoleRepository userRoleRepository;
	@Autowired
	private BackstageRoleRepository roleRepository;

	@Autowired
	public void setRepository(BackstageUserRepository repository) {
		super.setGenericDAO(repository);
		this.repository = repository;
	}

	public List<BackstageUser> list(Map<String, String> params, PageBean pageBean) {
		ConditionResult conditionResult = getQueryCondition(params, QueryType.LIST);
		List<BackstageUser> ret = repository.queryListBySql(conditionResult.getSql(), pageBean.getStartIndex(), pageBean.getPageSize(),
				conditionResult.getParams(), BackstageUser.class);
		conditionResult = getQueryCondition(params, QueryType.COUNT);
		pageBean.setTotal(repository.queryCountBySql(conditionResult.getSql(), conditionResult.getParams()));
		return ret;
	}

	private ConditionResult getQueryCondition(Map<String, String> searchMap, QueryType type) {
		StringBuilder sql = new StringBuilder();
		Map<String, Object> params = new HashMap<String, Object>();

		switch (type) {
		case LIST:
			sql.append(" select t.* ");

			break;
		case COUNT:
			sql.append(" select count(1)");
			break;
		default:
			break;
		}
		sql.append(" from BackstageUser t where 1=1 ");

		if (searchMap != null) {

		}
		if (type == QueryType.LIST) {
			sql.append(" order by t.createtime desc");
		}
		return new ConditionResult(sql.toString(), params);

	}

	/**
	 * 保存用户
	 * 
	 * @param user
	 * @param ids
	 * @return
	 */
	public Result<Object> saveUser(UserVo user, List<String> ids) {
		if (StringUtils.isNotBlank(user.getId())) {// 更新
			BackstageUser dbUser = repository.findOne(user.getId());
			if (dbUser != null) {

				List<BackstageUser> checkUsers = repository.findByUsername(user.getUsername());
				if (checkUsers != null) {
					for (BackstageUser checkUser : checkUsers) {
						if (!StringUtils.equals(checkUser.getId(), user.getId())) {
							return new Result<>(false, "更新失败，用户名已存在");
						}
					}
				}
				user.copy(dbUser);
				dbUser.setRolenames(saveUserRole(dbUser.getId(), ids));
				repository.save(dbUser);
				return new Result<>(true, "更新用户成功");
			}
			return new Result<>(true, "更新的用户不存在");
		} else {// 新增
			List<BackstageUser> checkUsers = repository.findByUsername(user.getUsername());
			if (checkUsers != null && checkUsers.size() > 0) {
				return new Result<>(false, "更新失败，用户名已存在");
			}

			BackstageUser dbUser = new BackstageUser();
			user.copy(dbUser);
			dbUser.setUserstatus("1");
			dbUser.setCreatetime(System.currentTimeMillis());
			repository.save(dbUser);
			dbUser.setRolenames(saveUserRole(dbUser.getId(), ids));
			repository.save(dbUser);
			return new Result<>(true, "新增用户成功");
		}
	}

	public String saveUserRole(String userId, List<String> roleIds) {
		// 删除之前的关联
		String sql = "delete from backstageuserrole  where userId=:userId";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		repository.executeSql(sql, params);

		StringBuffer roleNames = new StringBuffer();
		int length = 0;
		// 添加用户角色关联
		for (String roleId : roleIds) {
			BackstageRole role = roleRepository.findOne(roleId);
			if (role != null) {
				BackstageUserRole userRole = new BackstageUserRole();
				userRole.setRoleId(roleId);
				userRole.setUserId(userId);
				userRoleRepository.save(userRole);
				if (length < 3) {
					if (length == 0) {
						roleNames.append(role.getName());
					} else {
						roleNames.append(",").append(role.getName());
					}
					length++;
				} else if (length < 3) {
					roleNames.append("...");
					length++;
				}
			}
		}
		return roleNames.toString();
	}

	@Override
	public List<Map<String, Object>> findRoles(String id) {
		String sql = "select r.id from backstagerole r left join backstageuserrole ur on ur.roleId=r.id  where ur.userId=:userId";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", id);
		return repository.queryHumpListMapBySql(sql, params);
	}

	@Override
	public BackstageUser findByUsername(String username) {
		List<BackstageUser> users = repository.findByUsernameAndUserstatus(username, "1");
		if (users != null && users.size() > 0) {
			return users.get(0);
		}
		return null;
	}
}
